<script setup lang="ts">
import { markRaw, shallowRef } from 'vue'
import Test1 from '@/components/DynamicCom/Test1.vue'
import Test2 from '@/components/DynamicCom/Test2.vue'
import Test3 from '@/components/DynamicCom/Test3.vue'
import Test4 from '@/components/DynamicCom/Test4.vue'
import Test5 from '@/components/DynamicCom/Test5.vue'

// 定义组件类型
type DynamicComponent =
  | typeof Test1
  | typeof Test2
  | typeof Test3
  | typeof Test4
  | typeof Test5
  | string

//动态组件切换 使用shallowRef浅层监听优化性能
const currCom = shallowRef<DynamicComponent>(Test1)
const comArr: DynamicComponent[] = [
  markRaw(Test1),
  markRaw(Test2),
  markRaw(Test3),
  'Test4',
  'test5',
]

const changeTab = (type: number) => {
  currCom.value = comArr[type]
}
</script>

<script lang="ts">
//使用选项式components 结合组件字符串名的方式
export default {
  components: {
    Test4,
    Test5,
  },
}
</script>

<template>
  <div>
    <div class="tabBtn">
      <button @click="changeTab(0)">test1</button>
      <button @click="changeTab(1)">test2</button>
      <button @click="changeTab(2)">test3</button>
      <button @click="changeTab(3)">test4</button>
      <button @click="changeTab(4)">test5</button>
    </div>
    <keep-alive>
      <Suspense>
        <template #default>
          <!-- 动态组件 -->
          <component :is="currCom" v-if="typeof currCom !== 'string'"></component>
          <component :is="currCom" v-else v-bind="$attrs"></component>
          <!-- 其他组件 -->
        </template>
        <template #fallback>
          <el-skeleton />
        </template>
      </Suspense>
    </keep-alive>
  </div>
</template>

<style scoped lang="scss"></style>
